package com.jhf.youke.flink.domain.service;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import org.springframework.stereotype.Component;

/**
* @Description:
* @Param:
* @return:
* @Author: RHJ
* @Date: 2022/11/10
*/
@Component
public class DataSetService {
    private ExecutionEnvironment env;

    public DataSetService(){
         this.env = ExecutionEnvironment.createCollectionsEnvironment();
    }

    public void wordCount() throws Exception{
        String path = "E:\\workspace\\jhf-youke\\jhf-flink\\src\\main\\resources\\demo.txt";
        DataSource<String> inputSet = this.env.readTextFile(path);

        DataSet<Tuple2<String,Integer>> res = inputSet.flatMap(new WordFlatMapFunction())
                .groupBy(0)
                .sum(1);
        res.print();

    }


    public class WordFlatMapFunction implements FlatMapFunction<String, Tuple2<String,Integer>> {
        @Override
        public void flatMap(String str, Collector<Tuple2<String,Integer>> collector) throws Exception {
            String[] words = str.split(" ");
            for(String word : words){
                collector.collect(new Tuple2<>(word, 1));
            }
        }
    }

    public static void main(String[] args) throws Exception{
        DataSetService dataSetService = new DataSetService();
        dataSetService.wordCount();
    }



}
